package com.yihaodian.server;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.servlet.GzipFilter;
import org.mortbay.thread.QueuedThreadPool;

import com.yihaodian.api.common.Configs;
import com.yihaodian.common.util.NetUtil;

/**
 * nest search server.
 */
public class SearchJettyServer implements LifeCycleService {

	private static Logger logger = Logger.getLogger(SearchJettyServer.class);

	Server server = null;

	int port = 0;

	WebAppContext context = null;

	static final String SEARCH_CONTEXT_PATH = "/search";

	public SearchJettyServer(int port) {
		this.port = port;
		
		setNodePort(port);
	}

	void setNodePort(int port) {
		try {
			Configs.setProperty("cluster.properties", Configs.node_port_key, "" + port);
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void startup() {
		// init config
		String clusterId = Configs.getClusterId();
		logger.info("clusterId " + clusterId);

		server = new Server(port);

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setName("Search Broker(jetty) threads");
		threadPool.setMinThreads(20);
		threadPool.setMaxThreads(50);
		threadPool.setMaxIdleTimeMs(2000);
		server.setThreadPool(threadPool);

		context = new WebAppContext();

		context.setContextPath(SEARCH_CONTEXT_PATH);

		context.addFilter(GzipFilter.class, "/" + SEARCH_CONTEXT_PATH + "/*", 1);

		String webappPath = "./src/main/webapp";

		context.setResourceBase(webappPath);

		server.setHandler(context);

		server.setStopAtShutdown(true);

		try {
			server.start();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		logger.info(NetUtil.localAddress() +":"+ port + " startup ");
	}

	@Override
	public void shutdown() {
		try {
			server.stop();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}
